package Array;

public class 移除元素 {
    public int removeElement(int[] nums, int val) {
        // 快慢指针
        /*int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++)
            if (nums[fastIndex] != val) nums[slowIndex++] = nums[fastIndex];
        return slowIndex;*/

        // 相向双指针
        int left = 0;
        int right = nums.length - 1;
        while (right >= 0 && nums[right] == val) right--; //将right移到从右数第一个值不为val的位置
        while (left <= right) {
            if (nums[left] == val) { //left位置的元素需要移除
                //将right位置的元素移到left（覆盖），right位置移除
                nums[left] = nums[right];
                right--;
            }
            left++;
            while (right >= 0 && nums[right] == val) right--;
        }
        return left;
    }
}
